;
(function () {
  'use strict'

  window.b = {
    add: add,
    remove: remove,
    update: update,
    read: read,
    edit: edit
  }


  var article_list, last_id;

  init_data();

  // console.log('article_list:', article_list);

  function init_data() {
    article_list = s.get('article_list') || [];
    last_id = s.get('last_id') || 0;
  };

  function sync() {
    return s.set('article_list', article_list);
  }

  function find(id) {
    return article_list.find(function (article) {
      return article.id === id;
    })
  }

  function find_index(id) {
    return article_list.findIndex(function (article) {
      return article.id === id;
    })
  }

  function add(article) {
    if (!article || !article.title || !article.content)
      return;
    last_id++;
    article.id = last_id;

    article_list.push(article);
    sync();
    s.set('last_id', last_id);
  };

  function remove(id) {
    var shit_index = find_index(id);
    if (shit_index === -1) return;
    article_list.splice(shit_index, 1);
    sync();
  };

  function update(id, patch) {
    var article = article_list[find_index(id)];
    article_list[find_index(id)] = Object.assign({}, article, patch);
    sync();
  };

  function edit(element) {
    var oldhtml = element.innerHTML;
    var newobj = document.createElement('input');
    newobj.type = 'text';
    newobj.onblur = function () {
      element.innerHTML = this.value ? this.value : oldhtml;
    }
    element.innerHTML = '';
    element.appendChild(newobj);
    newobj.focus();
  }

  function read(id) {
    if (id)
      return find(id);
    return article_list;
  };

})();